package models

import (
	"errors"
	"fmt"
	"strconv"
	"time"
)

var (
	Objects map[string]*Object
)

type Object struct {
	ObjectId   string
	Score      int64
	PlayerName string
}

type MsgContent struct {
	Content string `json:"content"`
}

type MarkdownContent struct {
	Title string `json:"title"`
	Text  string `json:"text"`
}

type AtInfo struct {
	AtMobiles []string `json:"atMobiles"`
	IsAtAll   bool     `json:"isAtAll"`
}

type TextMsg struct {
	MsgType string     `json:"msgtype"`
	Text    MsgContent `json:"text"`
	At      AtInfo     `json:"at"`
}

type MarkdownMsg struct {
	MsgType  string          `json:"msgtype"`
	Markdown MarkdownContent `json:"markdown"`
	At       AtInfo          `json:"at"`
}

type Repo struct {
	Name        string `json:"name"`
	Url         string `json:"url"`
	Description string `json:"description"`
}

type Author struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

type Commit struct {
	Id        string `json:"id"`
	Message   string `json:"message"`
	Author    Author `json:"author"`
	Timestamp string `json:"timestamp"`
	Url       string `json:"url"`
}

type HookCommitInfo struct {
	Repository Repo    `json:"repository"`
	After      string  `json:"after"`
	Commits    []Commit `json:"commits"`
}

type CommitDigest struct {
	RepoName string
	Time     string
	Message  string
	Author   string
	CommitId string
	Url      string
}

func (cd *CommitDigest) Gen() string {
	str := fmt.Sprintf("#### **%s** \n", cd.RepoName)
	str += fmt.Sprintf("- 时间：%s \n", cd.Time)
	str += fmt.Sprintf("- 备注：%s \n", cd.Message)
	str += fmt.Sprintf("- 作者：%s \n", cd.Author)
	str += fmt.Sprintf("- ID：%s\n", cd.CommitId)
	str += fmt.Sprintf("- 链接：[点击查看](%s)\n", cd.Url)
	return str
}

func init() {
	Objects = make(map[string]*Object)
	Objects["hjkhsbnmn123"] = &Object{"hjkhsbnmn123", 100, "astaxie"}
	Objects["mjjkxsxsaa23"] = &Object{"mjjkxsxsaa23", 101, "someone"}
}

func AddOne(object Object) (ObjectId string) {
	object.ObjectId = "astaxie" + strconv.FormatInt(time.Now().UnixNano(), 10)
	Objects[object.ObjectId] = &object
	return object.ObjectId
}

func GetOne(ObjectId string) (object *Object, err error) {
	if v, ok := Objects[ObjectId]; ok {
		return v, nil
	}
	return nil, errors.New("ObjectId Not Exist")
}

func GetAll() map[string]*Object {
	return Objects
}

func Update(ObjectId string, Score int64) (err error) {
	if v, ok := Objects[ObjectId]; ok {
		v.Score = Score
		return nil
	}
	return errors.New("ObjectId Not Exist")
}

func Delete(ObjectId string) {
	delete(Objects, ObjectId)
}
